<?php

namespace app\shop\controller\projects;

use think\Controller;

class Order extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business.Business');
        $this->OrderModel = model('Project.Order');
        $this->ProjectModel = model('Project.Project');
        $this->ReceiveModel = model('Coupon.Receive');
    }

    public function index()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $status = $this->request->param('status', 'all', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit=10;
            $start=($page-1)*$limit;
            $where=[];
            if($status != 'all')
            {
                $where['order.status']=$status;
            }
            $list=$this->OrderModel->with(['project'])->where($where)->limit($start,$limit)->select();
            if($list)
            {
                $this->success('返回订单列表',null,$list);
                exit;
            }else
            {
                $this->error('暂无更多数据');
                exit;
            }
        }
    }

    public function add()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0, 'trim');
            $pid = $this->request->param('pid', 0, 'trim');
            $cid = $this->request->param('cid', 0, 'trim');
            // $order=$this->OrderModel->select();
            // halt($order);
            $business=$this->BusinessModel->find($busid);
            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }
            $project=$this->ProjectModel->find($pid);
            if(!$project)
            {
                $this->error('活动不存在');
                exit;
            }

            $receive=$this->ReceiveModel->with(['coupon'])->find($cid);
            // halt($receive->toArray());
            // 判断余额是否存在
            $total=$project['price'];
            if($receive)
            {
                $total=bcmul($total,$receive['coupon']['discount'],2);
            }

            $update=bcsub($business['money'],$total,2);

            if($update < 0)
            {
                $this->error('余额不足，请先充值');
                exit;
            }

            // 预约活动项目逻辑
            // 项目订单表 插入数据
            // 客户表 余额更新
            // 消费记录表 插入
            // 优惠劵表 coupon_receive 更新

            // 加载模型
            $OrderModel = model('Project.Order');
            $BusinessModel = model('Business.Business');
            $RecordModel = model('Business.Record');
            $ReceiveModel = model('Coupon.Receive');

            // 开启事务
            $OrderModel->startTrans();
            $BusinessModel->startTrans();
            $RecordModel->startTrans();
            $ReceiveModel->startTrans();

            // 订单表
            $OrderData=[
                'pid'=>$pid,
                'busid'=>$busid,
                'total'=>$total,
                'status'=>'0'
            ];

            if($receive)
            {
                $OrderData['receiveid']=$cid;
            }

            $OrderStatus=$OrderModel->validate("common/Project/Order")->save($OrderData);
            if($OrderStatus === FALSE)
            {
                $this->error($OrderModel->getError());
                exit;
            }

            // 更新客户表数据
            $BusinessData=[
                'id'=>$business['id'],
                'money'=>$update
            ];
            //验证器
            $validate = [
                [
                    'money' => ['number', '>=:0'],
                ],
                [
                    'money.number'      => '余额必须是数字类型',
                    'money.>='      => '余额必须大于等于0元',
                ]
            ];
            $BusinessStatus=$BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);
            if($BusinessStatus===FALSE)
            {
                $OrderModel->rollback();
                $this->error($BusinessModel->getError());
                exit;
            }

            // 插入消费表数据
            // 消费记录表插入数据
            $title=$project['title'];
            $content = "在活动预约上活动花费 ￥$total 元";
            $RecordData = [
                'total' => "-$total",
                'busid' => $busid,
                'content' => $content
            ];

            $RecordStatus=$RecordModel->validate('common/Business/Record')->save($RecordData);
            if($RecordStatus===FALSE)
            {
                $BusinessModel->rollback();
                $OrderModel->rollback();
                $this->error($RecordModel->getError());
                exit;
            }

            if($receive)
            {
                $ReceiveData=[
                    'id'=>$cid,
                    'updatetime'=>time(),
                    'status'=>'1'
                ];
                $ReceiveStatus=$ReceiveModel->isUpdate(true)->save($ReceiveData);
                if($ReceiveStatus===FALSE)
                {
                    $RecordModel->rollback();
                    $BusinessModel->rollback();
                    $OrderModel->rollback();
                    $this->error('更新优惠劵失败');
                    exit;
                }
            }
            
            if($OrderStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE)
            {
                $ReceiveModel->rollback();
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $OrderModel->rollback();
                $this->error('预约失败，请重新预约');
                exit;
            }else
            {
                $OrderModel->commit();
                $BusinessModel->commit();
                $RecordModel->commit();
                $ReceiveModel->commit();
                $this->success("预约成功",'/order/index');
                exit;
            }

        }
    }

    public function del()
    {
        if($this->request->isPost())
        {
            $busid=$this->request->param('busid',0,'trim');
            $id=$this->request->param('id',0,'trim');
         
            $business=$this->BusinessModel->find($busid);
            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }
            $order=$this->OrderModel->find($id);
            if(!$order)
            {
                $this->error('预约订单不存在');
                exit;
            }
            
            if($order['receiveid'])
            {
                $where=[
                    'id'=>$order['receiveid'],
                    'busid'=>$busid
                ];
                $receive=$this->ReceiveModel->where($where)->find();
            }
            // halt($receive->toArray());
            // exit;
            // if($receive)

            // 取消预约
            // 删除订单表 project_order 数据
            // 更新用户余额 business
            // 更新领取优惠劵表coupon_receive

            // 加载模型
            $OrderModel = model('Project.Order');
            $BusinessModel = model('Business.Business');
            $ReceiveModel = model('Coupon.Receive');

            // 开启事务
            $OrderModel->startTrans();
            $BusinessModel->startTrans();
            $ReceiveModel->startTrans(); 
            $OrderStatus=$OrderModel->where(['id'=>$id])->delete($id);
            if($OrderStatus === FALSE)
            {
                $this->error('删除订单失败');
                exit;
            }

            // 更新用户余额
            $money=$business['money'];
            $total=$order['total'];
            $update=bcadd($money,$total);

            // 更新客户表数据
            $BusinessData=[
                'id'=>$business['id'],
                'money'=>$update
            ];
            //验证器
            $validate = [
                [
                    'money' => ['number', '>=:0'],
                ],
                [
                    'money.number'      => '余额必须是数字类型',
                    'money.>='      => '余额必须大于等于0元',
                ]
            ];
            $BusinessStatus=$BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);
            if($BusinessStatus===FALSE)
            {
                $OrderModel->rollback();
                $this->error($BusinessModel->getError());
                exit;
            }

            if($order['receiveid'])
            {
                $ReceiveData=[
                    'id'=>$order['receiveid'],
                    'status'=>'0',
                    'updatetime'=>null
                ];
    
                $ReceiveStatus=$ReceiveModel->isUpdate(true)->save($ReceiveData);
                if($ReceiveStatus===FALSE)
                {
                    $BusinessModel->rollback();
                    $OrderModel->rollback();
                    $this->error('更新优惠劵失败');
                    exit;
                }
            }

            
            if($OrderStatus ===FALSE || $BusinessStatus === FALSE)
            {
                $ReceiveModel->rollback();
                $BusinessModel->rollback();
                $OrderModel->rollback();
                $this->error('取消订单失败');
                exit;
            }else
            {
                $OrderModel->commit();
                $BusinessModel->commit();
                $ReceiveModel->commit();
                $this->success('取消订单成功');
                exit;
            }
        }
    }

    public function comment()
    {
        if($this->request->isPost())
        {
            $id=$this->request->param('id',0,'trim');
            $comment=$this->request->param('comment',0,'trim');
            $order=$this->OrderModel->find($id);
            if(!$order)
            {
                $this->error('该预约订单不存在');
                exit;
            }
            // 组装数据
            $data=[
                'id'=>$id,
                'comment'=>$comment
            ];
            $result=$this->OrderModel->isUpdate(true)->save($data);
            if($result === FALSE)
            {
                $this->error('评价失败');
                exit;
            }
            $this->success('评价成功');
            exit;
        }
    }

    public function seeComment()
    {
        if($this->request->isPost())
        {
            $id=$this->request->param('id',0,'trim');
            $order=$this->OrderModel->find($id);
            if(!$order)
            {
                $this->error('该预约订单不存在');
                exit;
            }
            $this->success('返回订单详情',null,$order);
            exit;
        }
    }
}
